$(function() {
    layui.use('table', function() {
        var table = layui.table;
        var form = layui.table;
        getData()

        table.on('toolbar(table)', function(obj) {
            if (obj.event == 'search') {
                search()
            } else if (obj.event == 'add') {
                renderDialog('add')
            } else if (obj.event == 'del') {
                var checkStatus = table.checkStatus(obj.config.id);
                var data = checkStatus.data
                var ids = []
                for (var i = 0; i < data.length; i++) {
                    ids.push(data[i].id_prikey)
                }
                if (ids.length == 0) {
                    layer.alert('请先选择一个角色')
                } else {
                    del(ids)
                }
            }
        });

        table.on('tool(table)', function(obj) {
            var data = obj.data;
            if (obj.event == 'update') {
                getDataById(data.id_prikey)
            } else if (obj.event == 'addDetail') {
                getDetailById(data.id_prikey, 0, 'addRoleUser', '请选择要关联的用户')
            } else if (obj.event == 'removeDetail') {
                getDetailById(data.id_prikey, 1, 'removeRoleUser', '请选择要取消关联的用户')
            }
        })
    })
})

function getDetailById(id, type, url, title) {
    $.ajax({
        url: "getRoleUser",
        type: "POST",
        data: {
            id_prikey: id,
            flag: type
        },
        success: function(res) {
            if (res.code == 0) {
                var data = res.data
                renderDialogRole(data, id, url, title)
            }
        }
    });
}


function renderDialogRole(data, id, url, title) {
    var html = ''
    html += '<div class="layui-form">'
    html += '   <div class="layui-inline">'
    html += '       <label class="layui-form-label">搜索用户</label>'
    html += '       <div class="layui-input-inline">'
    html += '           <input type="text" id="value" placeholder="请输入姓名" autocomplete="off" class="layui-input">'
    html += '       </div>'
    html += '   </div>'
    html += '   <ul id="tree" class="ztree"></ul>'
    html += '</div>'
    layer.open({
        type: 1,
        area: ['400px', '500px'],
        content: html,
        title: title,
        btn: ['确定', '取消'],
        yes: function() {
            var treeObj = $.fn.zTree.getZTreeObj("tree");
            var nodes = treeObj.getCheckedNodes(true);
            var ids = []
            for (var i = 0; i < nodes.length; i++) {
                ids.push(nodes[i].id_prikey)
            }

            if (ids.length == 0) {
                layer.msg('请至少选择一个角色')
            } else {
                $.ajax({
                    url: url,
                    type: "POST",
                    data: {
                        id_prikey: id,
                        ids: ids
                    },
                    success: function(res) {
                        if (res.code == 0) {
                            layer.alert(res.msg, function() {
                                layer.closeAll();
                            })
                        } else {
                            layer.alert(res.msg)
                        }
                    }
                });
            }
        }
    });

    form.render()
    renderTree(data)

    $("#value").keyup(function(){
        var value = $(this).val()
        var dataArr = []
        for(var i=0;i<data.length;i++){
            var flag = data[i].showName.indexOf(value)
            if(flag != -1){
                dataArr.push(data[i])
            }
        }
        renderTree(dataArr)
    })

}

function renderTree(data) {
    var setting = {
        check: {
            enable: true,
        },
        data: {
            simpleData: {
                enable: true
            },
            key: {
                name: "showName"
            }
        },
        callback: {
            onClick: function() {
                var treeObj = $.fn.zTree.getZTreeObj("tree");
                var nodes = treeObj.getSelectedNodes();
                getTreeDetail(nodes[0].id)
                close()
            }
        }
    };

    $.fn.zTree.init($("#tree"), setting, data);
}

function getDataById(id) {
    $.ajax({
        url: "getRoleById",
        type: "POST",
        data: {
            id_prikey: id
        },
        success: function(res) {
            if (res.code == 0) {
                var data = res.data

                renderDialog('edit', data.id_prikey)
                $("#dialogName").val(data.name)
                $("#dialogShowName").val(data.showName)
                $("#dialogDisabled").val(data.disabled)


            } else {
                layer.alert(res.msg)
            }
        }
    });
}


function getData() {
    table.render({
        elem: '#table',
        method: 'post',
        url: 'getRolePagingData',
        height: $('.hb-page-left').height(),
        page: true,
        size: 'sm',
        defaultToolbar: [],
        loading: true,
        limit: 20,
        toolbar: '#toolbar',
        cols: [
            [{
                    checkbox: true
                }, {
                    field: 'name',
                    title: '名称',
                    align: 'center',
                },
                {
                    field: 'showName',
                    title: '描述',
                    align: 'center',
                },
                {
                    field: 'disabled',
                    title: '停用',
                    align: 'center',
                    templet: function(d) {
                        if (d.disabled == 0 || d.disabled == undefined) {
                            return "启用";
                        } else {
                            return "停用";
                        }
                    }
                },
                {
                    field: 'right',
                    title: '工具条',
                    align: 'center',
                    toolbar: '#bar'
                }
            ]
        ]
    });
}

function save(data, fun) {
    $.ajax({
        url: fun,
        type: "POST",
        data: data,
        success: function(res) {
            if (res.code == 0) {
                layer.alert(res.msg, function() {
                    layer.closeAll();
                    getData()
                })
            } else {
                layer.alert(res.msg)
            }
        }
    });
}

function del(ids) {
    $.ajax({
        url: "removeRole",
        type: "POST",
        data: {
            ids: ids
        },
        success: function(res) {
            if (res.code == 0) {
                layer.alert('删除成功', function() {
                    getData()
                    layer.closeAll();
                })
            } else {
                layer.alert(res.msg)
            }
        }
    });
}

function add() {
    var data = {
        name: $('#dialogName').val(),
        showName: $('#dialogShowName').val(),
        disabled: $('#dialogDisabled').val()
    }
    var fun = 'addRole'
    if ($('#dialogName').val() == '') {
        layer.msg('名称不能为空')
    } else if ($('#dialogShowName').val() == '') {
        layer.msg('描述不能为空')
    } else {
        save(data, fun)
    }
}

function edit(id) {
    var data = {
        name: $('#dialogName').val(),
        showName: $('#dialogShowName').val(),
        disabled: $('#dialogDisabled').val(),
        id_prikey: id
    }
    var fun = 'setRole'
    if ($('#dialogName').val() == '') {
        layer.msg('名称不能为空')
    } else if ($('#dialogShowName').val() == '') {
        layer.msg('描述不能为空')
    } else {
        save(data, fun)
    }
}

function renderDialog(type, id) {
    var html = ''
    html += '<div  class="layui-form" >'
    html += '    <div class="layui-form-item">'
    html += '        <label class="layui-form-label">名称</label>'
    html += '        <div class="layui-input-block">'
    html += '            <input type="text" id="dialogName" placeholder="请输入名称" autocomplete="off" class="layui-input">'
    html += '        </div>'
    html += '    </div>'
    html += '    <div class="layui-form-item">'
    html += '        <label class="layui-form-label">描述</label>'
    html += '        <div class="layui-input-block">'
    html += '            <input type="text" id="dialogShowName" placeholder="请输入描述" autocomplete="off" class="layui-input">'
    html += '        </div>'
    html += '    </div>'
    html += '    <div class="layui-form-item">'
    html += '        <label class="layui-form-label">停用</label>'
    html += '        <div class="layui-input-block">'
    html += '            <select id="dialogDisabled">'
    html += '                <option value="0">启用</option>'
    html += '                <option value="1">停用</option>'
    html += '            </select>'
    html += '        </div>'
    html += '    </div>'
    html += '</div>'

    var dialogData = {
        type: 1,
        content: html,
        btn: ['保存', '取消'],
    }

    if (type == 'add') {
        dialogData.title = '添加角色'
        dialogData.yes = function() {
            add()
        }
    } else {
        dialogData.title = '修改角色'
        dialogData.yes = function() {
            edit(id)
        }
    }

    layer.open(dialogData)

    form.render()


}


function search() {
    var data = {
        name: $("#name").val(),
        showName: $("#showName").val(),
        disabled: $("#disabled").val()
    }
    table.reload("table", {
        where: data,
        done: function() {
            $("#name").val(data.name)
            $("#showName").val(data.showName)
            $("#disabled").val(data.disabled)
        }
    });
}